package com.android.ailaoshan.index.listener;

import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.LocationManager;
import android.widget.TextView;

import com.android.ailaoshan.R;

import java.util.Iterator;

/**
 * GPS状态监听
 */
public class GPSStatusListener implements GpsStatus.Listener {

    private TextView gpsStatus;
    private LocationManager mLocationManager;

    public GPSStatusListener(TextView gpsStatus, LocationManager mLocationManager) {
        this.gpsStatus = gpsStatus;
        this.mLocationManager = mLocationManager;
    }

    @Override
    public void onGpsStatusChanged(int event) {
        switch (event){
            //卫星状态改变
            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:{
                GpsStatus gpsStatus = mLocationManager.getGpsStatus(null);
                //获取卫星颗数默认最大值
                int maxSatellites = gpsStatus.getMaxSatellites();
                //创建一个迭代器保存所有卫星
                Iterator<GpsSatellite> satelliteIterator = gpsStatus.getSatellites().iterator();
                int count = 0;
                while (satelliteIterator.hasNext() && count <= maxSatellites){
                    GpsSatellite satellite = satelliteIterator.next();
                    //已定位卫星颗数
                    if(satellite.usedInFix()){
                        count ++;
                    }
                }

                updateGPSStatus(count);
                break;
            }
        }
    }

    /**
     * 更新GPS状态
     */
    private void updateGPSStatus(int satelliteNum){
        if(satelliteNum < 3){
            gpsStatus.setText(R.string.gps_status_0);
        }else if(satelliteNum > 3 && satelliteNum <= 6){
            gpsStatus.setText(R.string.gps_status_1);
        }else if(satelliteNum > 6 && satelliteNum <= 12){
            gpsStatus.setText(R.string.gps_status_2);
        }else if(satelliteNum > 12 && satelliteNum <= 18){
            gpsStatus.setText(R.string.gps_status_3);
        }else if(satelliteNum > 18 && satelliteNum <= 20){
            gpsStatus.setText(R.string.gps_status_4);
        }else if(satelliteNum > 20){
            gpsStatus.setText(R.string.gps_status_5);
        }
    }
}
